/*
 * Sesame Inc.
 * Copyright (c) 2009 All Rights Reserved.
 */
package com.sesame.serviceimpl;

import java.util.List;
import java.util.Map;

import com.sesame.dao.MessageDAO;
import com.sesame.dao.UserDAO;
import com.sesame.domain.Message;
import com.sesame.domain.User;
import com.sesame.service.MessageService;
import com.sesame.toolkit.Page;

/**
 * @author shubeta
 * 
 */
public class MessageServiceImpl implements MessageService {

    private MessageDAO messageDAO;
    private UserDAO userDAO;

    public void setMessageDAO(MessageDAO messageDAO) {
        this.messageDAO = messageDAO;
    }

    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    public void deleteMessage(String message, String flag) {
        Message dbMessage = messageDAO
                .getMessageById(Integer.parseInt(message));
        if (!dbMessage.getFlag().equals("both")) {
            messageDAO.deleteMessageById(Integer.parseInt(message));
        } else {
            dbMessage.setFlag(flag);
            messageDAO.updateMessage(dbMessage);
        }

    }

    public void deleteMessage(String[] messages, String flag) {
        for (int i = 0; i < messages.length; i++) {
            Message dbMessage = messageDAO.getMessageById(Integer
                    .parseInt(messages[i]));
            if (!dbMessage.getFlag().equals("both")) {
                messageDAO.deleteMessageById(Integer.parseInt(messages[i]));
            } else {
                dbMessage.setFlag(flag);
                messageDAO.updateMessage(dbMessage);
            }
        }
    }

    public boolean isNewMessage(Message message, Map model) {
        User dbUser = userDAO.getUserByNickName(message.getReceiver());
        if (dbUser == null) {
            model.put("error_receiver", "该收件人不存在！");
            return false;
        } else {
            message.setReceiverId(dbUser.getId());
            messageDAO.addMessage(message);
            return true;
        }
    }

    public List<Message> listMessageByReceiver(Page page) {
        return messageDAO.getMessageByReceiver(page);
    }

    public List<Message> listMessageBySender(Page page) {
        return messageDAO.getMessageBySender(page);
    }

    public Message showMessage(Integer messageId) {
        Message dbMessage = messageDAO.getMessageById(messageId);
        dbMessage.setState("1");
        messageDAO.updateMessage(dbMessage);
        return dbMessage;
    }

    public Integer getMessageCount() {
        return messageDAO.getMessageCount();
    }

    public Integer getSendedMessageCount(Integer senderId) {
        return messageDAO.getSendedMessageCount(senderId);
    }

    public Integer getReceivedMessageCount(Integer receiverId) {
        return messageDAO.getReceivedMessageCount(receiverId);
    }

}